//
// Pcw.FindText.cs
//
// Author: 
//  Fredy Ramirez <framirez@pacificcoolwave.com>
//
// Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)
//
//  Creation date: Sep 20, 2011
//  Last modification: 

/*
The MIT License

Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

using System;
using System.Text.RegularExpressions;
using Gtk;
using System.Collections.Generic;

namespace Pcw.Addins.Search
{
	public class FindText
	{	
		private TextBuffer buffer;
		private List<StringFound> founds = new List<StringFound>();
		private string tag_name = "tag_find_replace";
		private string tag_color;
		private FindGui gui;
		
		public List<StringFound> Founds {
			get {
				return founds;
			}
		}
		
		public TextBuffer Buffer {
			set {
				SetBuffer(value);
			}
		}
		
		public FindText (string tagColor) : this(null, tagColor)
		{
		}
		
		public FindText (TextBuffer textBuffer, string tagColor)
		{			
			tag_color = tagColor;			
			SetBuffer(textBuffer);
		}

		public int Find (string findString) 
		{
			return Find(findString, false, false);
		}
		
		public int Find (string findString, bool ignoreCase, bool useRegex) 
		{
			if (buffer == null) 
				throw new InvalidOperationException ("TextBuffer buffer must be set. Use 'Buffer' property to pass a buffer object.");
			
			founds.Clear();
			buffer.RemoveTag (tag_name, buffer.StartIter, buffer.EndIter);
			
			if (String.IsNullOrEmpty(findString))
				return 0;
			
			if (useRegex) 
				return FindWithRegex(findString, null, ignoreCase);
			else
				return FindSimple(findString, null, ignoreCase);
		
		}
		
		public int Replace (string findString, string newString, bool ignoreCase, bool useRegex) 
		{
			founds.Clear();
			buffer.RemoveTag (tag_name, buffer.StartIter, buffer.EndIter);
			
			if (useRegex)
				FindWithRegex(findString, newString, ignoreCase);
			else
				FindSimple(findString, newString, ignoreCase);
			
			return founds.Count;
		}
		
		public void ShowFind(Window parent, bool isReplace)
		{
			if (FindGui.IsShown)
				return;
			
			gui = new FindGui(this, isReplace, parent);
			
		}
		
		public void CloseFind()
		{
			if (!FindGui.IsShown)
				return;
			
			gui.Close();
			
		}		
		
		private int FindSimple(string findString, string replaceString, bool ignoreCase)
		{
			int index = 0;
			
			while (index > -1)
			{
				if (ignoreCase)
					index = buffer.Text.IndexOf(findString, index, StringComparison.CurrentCultureIgnoreCase);
				else
					index = buffer.Text.IndexOf(findString, index);
				
				if (index > -1){
					if (replaceString == null){
						founds.Add(new StringFound(buffer.Text.Substring(index, findString.Length), index));
					}
					else {
						buffer.Text = buffer.Text.Substring(0, index) + replaceString + buffer.Text.Substring(index + findString.Length);						
						if (!String.IsNullOrEmpty(replaceString)) 
							founds.Add(new StringFound(buffer.Text.Substring(index, replaceString.Length), index));
					}
					
					index++;
				}
			}
			
			ApplyTag();
			
			return founds.Count;
			
		}
		
		private int FindWithRegex (string findString, string replaceString, bool ignoreCase) 
		{			
			RegexOptions options = new RegexOptions();
			options |= RegexOptions.Singleline;
			options |= RegexOptions.Multiline;
			if (ignoreCase)
				options |= RegexOptions.IgnoreCase;	
			
			Regex regex = new Regex (findString, options);
			
			if (regex.IsMatch(buffer.Text)) {

				Match[] ma = FindSubstrings(regex, buffer.Text, findString);
				
				int i = 0;
				foreach(Match m in ma)
				{
					if (replaceString == null) {
						founds.Add(new StringFound(buffer.Text.Substring(m.Index, ma.GetValue(i).ToString().Length), m.Index));
					}
					else {
						buffer.Text = buffer.Text.Substring(0, m.Index) + replaceString + buffer.Text.Substring(m.Index + findString.Length);
						if (!String.IsNullOrEmpty(replaceString)) 
							founds.Add(new StringFound(buffer.Text.Substring(m.Index, replaceString.Length), m.Index));
					}
					i++;
				}
			}
			
			ApplyTag();
			
			return founds.Count;
			
		}
		
		private Match[] FindSubstrings(Regex regex, string source, string matchPattern)
		{ 
			Match[] retArray = null;

			MatchCollection theMatches = regex.Matches(source);
	
			retArray = new Match[theMatches.Count];
			theMatches.CopyTo(retArray, 0);

			return retArray;
		}
		
		private void SetBuffer(TextBuffer textBuffer)
		{			
			if (textBuffer == null)
				return;
			
			buffer = textBuffer;
			
			TextTag tag;
			tag = buffer.TagTable.Lookup(tag_name);
			
			if (tag == null) {
				tag  = new TextTag (tag_name);
				tag.Background = tag_color;
				buffer.TagTable.Add (tag);
			}
		}
		
		private void ApplyTag()
		{
			foreach (StringFound s in founds)
			{
				TextIter iter = buffer.StartIter;
				iter.ForwardChars(s.Position);
				TextIter iter2 = iter;
				iter2.ForwardChars(s.Text.Length);
				buffer.ApplyTag(tag_name, iter, iter2);
			}			
		}
	}
	
	public class StringFound 
	{
		private string str;
		private int pos;
	
		public string Text {
			get {
				return str;
			}
		}
		
		public int Position {
			get {
				return pos;
			}
		}
		
		public StringFound (string stringFound, int position)
		{
			str = stringFound;
			pos = position;
		}
	}
}

